package com.ruoyi.web.controller.tool;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.utils.DictUtils;
import com.ruoyi.webContent.domain.HostCasEntry;
import com.ruoyi.webContent.domain.PlCalculateResult;
import com.ruoyi.webContent.domain.PlMatchType;
import com.ruoyi.webContent.domain.PlTeam;
import com.ruoyi.webContent.service.IPlMatchTypeService;
import com.ruoyi.webContent.service.IPlTeamService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.util.MapUtils;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.*;

public class PlDataMakeBestUtils {

    protected static final Logger logger = LoggerFactory.getLogger(PlDataMakeBestUtils.class);

    /**
     * 各个网站详情封装方法
     * @param host
     * @param contents matchId:content
     */
    public static void hostContentCas(SysDictData host,SysDictData game,JSONObject contents){
        //运用反射的方法
        Class<PlDataMakeBestUtils> plDataMakeBestUtils = PlDataMakeBestUtils.class;
        if(contents==null){
            logger.info("封装数据为空！！！>>>游戏名称："+game.getDictLabel()+",>>>网站名称："+host.getDictLabel());
            return;
        }
        for (String matchId :contents.keySet()) {
            JSONObject matchContent = contents.getJSONObject(matchId);
            try {
                Method host_contentCase = plDataMakeBestUtils.getDeclaredMethod(host.getDictLabel()+"_contentCase", SysDictData.class, JSONObject.class);
                HostCasEntry hostCasEntry = (HostCasEntry)host_contentCase.invoke(plDataMakeBestUtils.newInstance(),game,matchContent);
                hostCasEntry.setGameName(game.getDictLabel());
                hostCasEntry.setGameValue(game.getDictValue());
                hostCasEntry.setHostName(host.getDictLabel());
                hostCasEntry.setHostRemark(host.getRemark());
                PlDataSetUtils.setHostMatchIdAttr(host.getDictLabel(),matchId,hostCasEntry);
            }catch (Exception e){
                logger.error("比赛详情信息封装异常！！！方法名："+host.getDictLabel()+"_contentCase,>>>游戏名称："+game.getDictLabel()+",>>>比赛id"+matchId+"报错信息："+ ExceptionUtil.getExceptionMessage(e));
            }
        }
    }

    //赔率计算和展示信息封装
    public static List<PlCalculateResult> getCalRes(SysDictData game) {
        //获取所有队伍详情
        //各个网站分别进行信息封装
        List<SysDictData> pl_host = DictUtils.getDictCache("pl_rest_url");
        for (SysDictData host : pl_host) {
            JSONObject host_match_contents = PlDataSetUtils.getHostgameAllContent(host.getDictLabel(),game.getDictLabel());
            //数据经过加工后存入数据中心
            hostContentCas(host,game,host_match_contents);
            logger.info("比赛详情信息封装>>>完成！！！方法名："+host.getDictLabel()+"_contentCase,>>>游戏名称："+game.getDictLabel());
        }
        //所有结果信息集合
        List<PlCalculateResult> all_result = new ArrayList<>();
        JSONObject hostABSameMatch = PlDataSetUtils.getGameHostABSameMatch(game.getDictLabel());
        if(hostABSameMatch==null){
            logger.info("匹配相同比赛为空！！！>>>游戏名称："+game.getDictLabel());
            return null;
        }
        //遍历网站的组合
        for (String hostA_hostB:hostABSameMatch.keySet()) {
            String[] hosts = hostA_hostB.split("_");
            String hostA = hosts[0];
            String hostB = hosts[1];
            JSONArray hostMatchs = hostABSameMatch.getJSONArray(hostA_hostB);
            //遍历比赛的组合
            for (Object match : hostMatchs) {
                Map<String,String> matchId = (Map)match;
                HostCasEntry hostMatchIdAttrA = PlDataSetUtils.getHostMatchIdAttr(hostA, matchId.get(hostA));
                HostCasEntry hostMatchIdAttrB = PlDataSetUtils.getHostMatchIdAttr(hostB, matchId.get(hostB));
                //顺序打乱达到两边都比对的效果
                List<PlCalculateResult> res1 = calculate(hostMatchIdAttrA, hostMatchIdAttrB);
                List<PlCalculateResult> res2 = calculate(hostMatchIdAttrB, hostMatchIdAttrA);
                all_result.addAll(res1);
                all_result.addAll(res2);
            }
        }
        return all_result;

    }
    /**
     * 计算是否有利润
     * @param hostMatchIdAttrA 网站A数据
     * @param hostMatchIdAttrB 网站B数据
     * @return
     */
    public static List<PlCalculateResult> calculate(HostCasEntry hostMatchIdAttrA,HostCasEntry hostMatchIdAttrB) {
        List<PlCalculateResult> res_list = new ArrayList<>();
        //公式计算是否有利润
        for (PlMatchType plMap : getPlMatchTypes(hostMatchIdAttrA.getGameValue())) {
            String matchType = plMap.getMatchType();
            Map<String,String> hostA_oddsMap = hostMatchIdAttrA.getMarkets().get(matchType);
            Map<String,String> hostB_oddsMap = hostMatchIdAttrB.getMarkets().get(matchType);
            String teamId1_hostA = hostMatchIdAttrA.getHomeTeamLocalId();
            String teamId2_hostA = hostMatchIdAttrA.getAwayTeamLocalId();
            String teamId1_hostB = hostMatchIdAttrB.getHomeTeamLocalId();
//            String teamId2_hostB = hostMatchIdAttrB.getAwayTeamLocalId();
            //若两个网站的主队客队不一致,主队本地ID必须大于客队本地ID，即调整网站A数据
            if(Integer.parseInt(teamId1_hostA)>Integer.parseInt(teamId1_hostB)){
                //将网站A主队客队调换
                String temp_homeId = hostMatchIdAttrA.getHomeTeamId();
                String temp_homeName = hostMatchIdAttrA.getHomeTeamName();
                hostMatchIdAttrA.setHomeTeamId(hostMatchIdAttrA.getAwayTeamId());
                hostMatchIdAttrA.setHomeTeamName(hostMatchIdAttrA.getAwayTeamName());
                hostMatchIdAttrA.setHomeTeamLocalId(teamId2_hostA);
                hostMatchIdAttrA.setAwayTeamId(temp_homeId);
                hostMatchIdAttrA.setAwayTeamName(temp_homeName);
                hostMatchIdAttrA.setAwayTeamLocalId(teamId1_hostA);
            }
            //计算1
            PlCalculateResult res = new PlCalculateResult();
            if(MapUtils.isEmpty(hostA_oddsMap)||MapUtils.isEmpty(hostB_oddsMap)){
                continue;
            }
            res.setHostA(hostMatchIdAttrA.getHostRemark());
            res.setHostB(hostMatchIdAttrB.getHostRemark());
            res.setHostACode(hostMatchIdAttrA.getMatchId());
            res.setHostBCode(hostMatchIdAttrB.getMatchId());
            res.setGameName(hostMatchIdAttrA.getGameValue());
            res.setPlType(plMap.getMatchTypeCh());
            res.setMatchOrderType(plMap.getMatchOrderType());
            res.setStartDate(hostMatchIdAttrB.getStartTime());
            res.setHostAmarketId(hostA_oddsMap.get("marketId"));
            res.setHostBmarketId(hostB_oddsMap.get("marketId"));

            if(plMap.getMatchOrderType().equals("1")||plMap.getMatchOrderType().equals("5")){//队伍和VIP队伍
                res.setHostAView(hostMatchIdAttrA.getMatchName()+"("+hostMatchIdAttrA.getHomeTeamName()+")");
                res.setHostBView(hostMatchIdAttrB.getMatchName()+"("+hostMatchIdAttrB.getAwayTeamName()+")");
                String hostA_home_odd = hostA_oddsMap.get(hostMatchIdAttrA.getHomeTeamLocalId());
                String hostB_away_odd = hostB_oddsMap.get(hostMatchIdAttrA.getAwayTeamLocalId());
                PlCalculateResult type1Res = resMake(res, hostA_home_odd, hostB_away_odd);
                //存入
                res_list.add(type1Res);
            }else if(plMap.getMatchOrderType().equals("2")){//杀敌数让分
                //每一轮比对用A的+比对B的-
                for (String keyA:hostA_oddsMap.keySet()) {
                    if(keyA.contains(hostMatchIdAttrA.getHomeTeamLocalId()+"+")){
                        String value = keyA.replace(hostMatchIdAttrA.getHomeTeamLocalId()+"+","").trim();
                        String keyB = hostMatchIdAttrA.getAwayTeamLocalId()+"-"+value;
                        if(hostB_oddsMap.containsKey(keyB)){
                            res.setHostAView(hostMatchIdAttrA.getMatchName()+"("+hostMatchIdAttrA.getHomeTeamName()+"+"+value+")");
                            res.setHostBView(hostMatchIdAttrB.getMatchName()+"("+hostMatchIdAttrB.getAwayTeamName()+"-"+value+")");
                            PlCalculateResult type1Res = resMake(res, hostA_oddsMap.get(keyA), hostB_oddsMap.get(keyB));
                            //存入
                            res_list.add(type1Res);
                        }
                    }
                }
            }else if(plMap.getMatchOrderType().equals("3")){//大小
                //每一轮比对用A的大于比对B的小于
                for (String keyA:hostA_oddsMap.keySet()) {
                    if(keyA.contains("大")){
                        String keyB = keyA.replace("大","小");
                        if(hostB_oddsMap.containsKey(keyB)){
                            res.setHostAView(hostMatchIdAttrA.getMatchName()+"("+keyA+")");
                            res.setHostBView(hostMatchIdAttrB.getMatchName()+"("+keyB+")");
                            PlCalculateResult type1Res = resMake(res, hostA_oddsMap.get(keyA), hostB_oddsMap.get(keyB));
                            //存入
                            res_list.add(type1Res);
                        }
                    }
                }
            }else if(plMap.getMatchOrderType().equals("4")){//让局
                String matchType_name = plMap.getMatchType();
                String value = matchType_name.substring(matchType_name.indexOf("(")+1,matchType_name.indexOf(")"));
                //组装出可能的key
                String hostA_home_key1 = hostMatchIdAttrA.getHomeTeamLocalId()+"+"+value;
                String hostA_home_key2 = hostMatchIdAttrA.getHomeTeamLocalId()+"-"+value;
                if(hostA_oddsMap.containsKey(hostA_home_key1)&&hostB_oddsMap.containsKey(hostA_home_key1)){
                    String hostA_away_key1 = hostMatchIdAttrA.getAwayTeamLocalId()+"-"+value;
                    String hostA_home_odd = hostA_oddsMap.get(hostA_home_key1);
                    String hostB_away_odd = hostB_oddsMap.get(hostA_away_key1);
                    res.setHostAView(hostMatchIdAttrA.getMatchName()+"("+hostMatchIdAttrA.getHomeTeamName()+"+"+value+")");
                    res.setHostBView(hostMatchIdAttrB.getMatchName()+"("+hostMatchIdAttrB.getAwayTeamName()+"-"+value+")");
                    PlCalculateResult type4Res1 = resMake(res, hostA_home_odd, hostB_away_odd);
                    //存入
                    res_list.add(type4Res1);
                }
                if(hostA_oddsMap.containsKey(hostA_home_key2)&&hostB_oddsMap.containsKey(hostA_home_key2)){
                    String hostA_away_key2 = hostMatchIdAttrA.getAwayTeamLocalId()+"+"+value;
                    String hostA_home_odd = hostA_oddsMap.get(hostA_home_key2);
                    String hostB_away_odd = hostB_oddsMap.get(hostA_away_key2);
                    res.setHostAView(hostMatchIdAttrA.getMatchName()+"("+hostMatchIdAttrA.getHomeTeamName()+"-"+value+")");
                    res.setHostBView(hostMatchIdAttrB.getMatchName()+"("+hostMatchIdAttrB.getAwayTeamName()+"+"+value+")");
                    PlCalculateResult type4Res2 = resMake(res, hostA_home_odd, hostB_away_odd);
                    //存入
                    res_list.add(type4Res2);
                }

            }
        }
        return res_list;
    }

    /**
     * 返回结果的补充方法
     * @param res
     * @param hostA_home_odd
     * @param hostB_away_odd
     */
    public static PlCalculateResult resMake(PlCalculateResult res, String hostA_home_odd, String hostB_away_odd) {
        res.setHostAPl(hostA_home_odd);
        res.setHostBPl(hostB_away_odd);
        BigDecimal muthRes = new BigDecimal(hostA_home_odd).subtract(new BigDecimal(1))
                .multiply(new BigDecimal(hostB_away_odd)).subtract(new BigDecimal(hostA_home_odd));
        Long calRes = (long)Math.floor(muthRes.doubleValue()*100);
        res.setRes(calRes);
        return res;
    }

    /**
     * //根据游戏id获取已有赔率类型
     * @param gameValue
     * @param isIpdate 是否更新
     * @return
     */
    private static Map<String,List<PlMatchType>> gameValue_MatchType = new HashMap<>();

    public static List<PlMatchType> getPlMatchTypes(String gameValue,boolean ...isIpdate) {
        if(isIpdate.length>0&&isIpdate[0]==true){
            gameValue_MatchType.clear();;
            //刷新所有赔率类型
            IPlMatchTypeService matchTypeService = (IPlMatchTypeService) ApplicationContextUtil.getBean("plMatchTypeServiceImpl");
            List<SysDictData> game_name_arr = DictUtils.getDictCache("game_name_arr");
            for (SysDictData dic:game_name_arr) {
                PlMatchType p = new PlMatchType();
                p.setGameName(dic.getDictValue());
                gameValue_MatchType.put(dic.getDictValue(),matchTypeService.selectPlMatchTypeList(p));
            }
            logger.info("刷新所有赔率类型！！！");
        }
        return gameValue_MatchType.get(gameValue);
    }

    //雷电竞数据转换成 赔率类型名称 ：（队伍：赔率）
    public static HostCasEntry ldj_contentCase(SysDictData game, JSONObject content){
        //转换
        HostCasEntry ldjEntry = new HostCasEntry();
        ldjEntry.setMatchId(content.getString("id"));
        ldjEntry.setMatchName(content.getString("match_name"));
        ldjEntry.setStartTime(content.getString("start_time"));
        ldjEntry.setHomeTeamName(JSONPath.read(content.toJSONString(),"$.team[1].team_short_name").toString());
        ldjEntry.setHomeTeamId(JSONPath.read(content.toJSONString(),"$.team[1].team_id").toString());
        ldjEntry.setHomeTeamLocalId(getTeamId("ldj",ldjEntry.getHomeTeamId()));
        ldjEntry.setAwayTeamName(JSONPath.read(content.toJSONString(),"$.team[0].team_short_name").toString());
        ldjEntry.setAwayTeamId(JSONPath.read(content.toJSONString(),"$.team[0].team_id").toString());
        ldjEntry.setAwayTeamLocalId(getTeamId("ldj",ldjEntry.getAwayTeamId()));
        List<PlMatchType> plMatchTypes = getPlMatchTypes(game.getDictValue());
        //雷电竞数据处理
        //数据处理完成后的集合 自赔率类型：（队伍：赔率）
        Map<String,Map> host_match_type = new HashMap<>();
        JSONArray odds = content.getJSONArray("odds");
        for (Object odd_l : odds) {
            JSONObject oddJsonObject = JSONObject.parseObject(odd_l.toString());
            for (PlMatchType plMap : plMatchTypes) {
                Map<String, String> l_teamId_odd = ldj_getMatchType(oddJsonObject,plMap);
                if(l_teamId_odd.size()>0){
                    String l_matchType_name = plMap.getMatchType();
                    Map<String, String> l_match_odds = host_match_type.get(l_matchType_name);
                    if (l_match_odds == null) {
                        l_match_odds = new HashMap<>();
                    }
                    l_match_odds.putAll(l_teamId_odd);
                    host_match_type.put(l_matchType_name,l_match_odds);
                    break;
                }
            }
        }
        ldjEntry.setMarkets(host_match_type);
        return ldjEntry;
    }

    //亚博数据转换（content为parentMatch[0]）
    public static HostCasEntry yb_contentCase(SysDictData game, JSONObject content){
        //转换
        HostCasEntry ybEntry = new HostCasEntry();
        ybEntry.setMatchId(content.getString("PMatchNo"));
        ybEntry.setMatchName(content.getString("PHTName")+"-vs-"+content.getString("PATName"));
        String startTime=content.getString("PMCDate").replace("T"," ");
        Date startDate = DateUtils.addHours(DateUtils.parseDate(startTime.substring(0, 19)), 12);
        ybEntry.setStartTime(DateUtils.dateTimeMine(startDate));
        ybEntry.setHomeTeamName(content.getString("PHTName"));
        ybEntry.setHomeTeamId(content.getString("PHTId"));
        ybEntry.setHomeTeamLocalId(getTeamId("yb",ybEntry.getHomeTeamId()));
        ybEntry.setAwayTeamName(content.getString("PATName"));
        ybEntry.setAwayTeamId(content.getString("PATId"));
        ybEntry.setAwayTeamLocalId(getTeamId("yb",ybEntry.getAwayTeamId()));
        //获取亚博parentMatch结构
        Map<String, String> yb_teamMap = new HashMap<>();
        //亚博队伍组装
        yb_teamMap.put("1",ybEntry.getHomeTeamLocalId());
        yb_teamMap.put("2",ybEntry.getAwayTeamLocalId());
        //亚博数据处理
        //数据处理完成后的集合 自赔率类型：（队伍：赔率）
        Map<String,Map> host_match_type = new HashMap<>();
        JSONArray MatchArray = content.getJSONArray("Match");
        for (Object matchObject : MatchArray) {
            JSONObject matchJsonObject = JSONObject.parseObject(matchObject.toString());
            for (PlMatchType plMap : getPlMatchTypes(game.getDictValue())) {
                Map<String, String> yb_teamid_odd = yb_getMatchMap(yb_teamMap, matchJsonObject, plMap);
                if(yb_teamid_odd.size()>0){
                    yb_teamid_odd.put("marketId",matchJsonObject.getString("MatchNo"));
                    String yb_matchType_name = plMap.getMatchType();
                    host_match_type.put(yb_matchType_name,yb_teamid_odd);
                    break;
                }
            }
        }
        ybEntry.setMarkets(host_match_type);
        return ybEntry;
    }

    /**
     * 雷火数据转换成 赔率类型名称 ：（队伍：赔率）
     * @param game
     * @param content
     * @return
     */
    public static HostCasEntry lh_contentCase(SysDictData game, JSONObject content) {
        //转换
        HostCasEntry lhEntry = new HostCasEntry();
        lhEntry.setMatchId(content.getString("event_id"));
        lhEntry.setStartTime(content.getString("start_datetime"));
        lhEntry.setHomeTeamName(JSONPath.read(content.toJSONString(),"$.home.team_name").toString());
        lhEntry.setHomeTeamId(JSONPath.read(content.toJSONString(),"$.home.team_id").toString());
        lhEntry.setHomeTeamLocalId(getTeamId("lh",lhEntry.getHomeTeamId()));
        lhEntry.setAwayTeamName(JSONPath.read(content.toJSONString(),"$.away.team_name").toString());
        lhEntry.setAwayTeamId(JSONPath.read(content.toJSONString(),"$.away.team_id").toString());
        lhEntry.setAwayTeamLocalId(getTeamId("lh",lhEntry.getAwayTeamId()));
        lhEntry.setMatchName(lhEntry.getHomeTeamName()+"-vs-"+lhEntry.getAwayTeamName());
        //获取雷火markets结构
        JSONArray markets = content.getJSONArray("markets");
        Map<String,Map<String,String>> match_type = new HashMap<>();
        List<PlMatchType> plMatchTypes = getPlMatchTypes(game.getDictValue());
        //处理赔率为 赔率名称（名称_类型_第几局）：Map(队伍，赔率)
        for (Object market:markets) {
            JSONObject market_json = JSON.parseObject(market.toString());
//            String typeName = market_json.getString("bet_type_name")+"_"+market_json.getString("market_option")+"_"+market_json.getString("map_num");
            String typeName = market_json.getString("market_name").replace(" ", "");
            for (PlMatchType plMap : plMatchTypes) {
                try{
                    if(plMap.getLhMatchName().replace(" ", "").equals(typeName)){
                        JSONArray selectionArr = market_json.getJSONArray("selection");
                        //取出主队和客队
                        JSONObject home_team = JSONObject.parseObject(selectionArr.get(0).toString());
                        JSONObject away_team = JSONObject.parseObject(selectionArr.get(1).toString());
                        if(home_team.getString("status").equals("open")){
                            Map<String,String> team_odd = new HashMap<>();
                            if(plMap.getMatchOrderType().equals("1")||plMap.getMatchOrderType().equals("5")){//队伍和VIP队伍
                                team_odd.put(getTeamId("lh",lhEntry.getHomeTeamId()),home_team.getString("euro_odds"));
                                team_odd.put(getTeamId("lh",lhEntry.getAwayTeamId()),away_team.getString("euro_odds"));
                                team_odd.put("marketId",market_json.getString("market_id"));
                            }else if(plMap.getMatchOrderType().equals("2")){//让击杀
                                team_odd.put(getTeamId("lh",lhEntry.getHomeTeamId())+home_team.getString("handicap"),home_team.getString("euro_odds"));
                                team_odd.put(getTeamId("lh",lhEntry.getAwayTeamId())+away_team.getString("handicap"),away_team.getString("euro_odds"));
                                team_odd.put("marketId",market_json.getString("market_id"));
                            }else if(plMap.getMatchOrderType().equals("3")){//大小
                                team_odd.put(home_team.getString("bet_type_selection_name")+home_team.getString("handicap"),home_team.getString("euro_odds"));
                                team_odd.put(away_team.getString("bet_type_selection_name")+away_team.getString("handicap"),away_team.getString("euro_odds"));
                                team_odd.put("marketId_"+home_team.getString("handicap"),market_json.getString("market_id"));
                            }else if(plMap.getMatchOrderType().equals("4")){//让分
                                String matchType_name = plMap.getMatchType();
                                String value = matchType_name.substring(matchType_name.indexOf("(")+1,matchType_name.indexOf(")"));
                                //正负1.5字符串都是包含1.5的
                                if(home_team.getString("handicap").contains(value)){
                                    team_odd.put(getTeamId("lh",lhEntry.getHomeTeamId())+home_team.getString("handicap"),home_team.getString("euro_odds"));
                                    team_odd.put(getTeamId("lh",lhEntry.getAwayTeamId())+away_team.getString("handicap"),away_team.getString("euro_odds"));
                                }
                                team_odd.put("marketId",market_json.getString("market_id"));
                            }
                            typeName = plMap.getMatchType();
                            Map<String, String> type4map = match_type.get(typeName);
                            if(type4map ==null){
                                match_type.put(typeName,team_odd);
                            }else {
                                type4map.putAll(team_odd);
                                match_type.put(typeName,type4map);
                            }
                        }
                        break;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        lhEntry.setMarkets(match_type);
        return lhEntry;
    }
    /**
     * 通过队伍名称获取队伍字典
     * @param gameName
     * @return
     */
    public static SysDictData getGameDictByGameName(String gameName) {
        List<SysDictData> game_name_arr = DictUtils.getDictCache("game_name_arr");
        SysDictData gameDict = null;
        for (SysDictData dic:game_name_arr) {
            if(dic.getDictLabel().equals(gameName)){
                gameDict=dic;
                break;
            }
        }
        return gameDict;
    }
    /**
     * 获取所有比赛match后的信息处理，最终得出不同网站间的相同比赛组合
     */
    public static void allMatchDataMake(String gameName){
        List<SysDictData> pl_host = DictUtils.getDictCache("pl_rest_url");
        //所有比赛包装为host:Map(队伍id:队伍id,比赛id)
        JSONObject teamId_gameId = new JSONObject();
        for (SysDictData host:pl_host) {
            JSONArray MatchAll = PlDataSetUtils.getHostgameAllMatch(host.getDictLabel(),gameName);
            for (Object d : MatchAll) {
                JSONObject dataJsonObject = JSONObject.parseObject(d.toString());
                Map map = matchMesCase(dataJsonObject, host.getDictLabel());
                if(map.size()>0){
                    //此处写的复杂是为了简化代码，多重map赋值比较麻烦
                    String next = map.keySet().iterator().next().toString();
                    JSONPath.set(teamId_gameId,"$."+host.getDictLabel()+"."+next,map.get(next));
                }
            }
        }
        //组装比赛对应组合,去除组合中的重复部分，即每次忽略相同的并在第二层中减去第一层已经使用过的，避免无效对应
        List<String> host_zuhe = new ArrayList<>();
        Set<String> hostNone = new HashSet<>();
        for (SysDictData hostA:pl_host) {
            hostNone.add(hostA.getDictLabel());
            for (SysDictData hostB:pl_host) {
                if(hostNone.contains(hostB.getDictLabel())==false){
                    host_zuhe.add(hostA.getDictLabel()+":"+hostB.getDictLabel());
                }
            }
        }
        //遍历组合和游戏名，得到下面的数据结构
        //hostA_hostB:{hostA_code:id,hostB_code:id}
        for (String hostNameAB:host_zuhe) {
            String[] split = hostNameAB.split(":");
            String hostA_name = split[0];
            String hostB_name = split[1];
            JSONObject hostA_map = teamId_gameId.getJSONObject(hostA_name);
            JSONObject hostB_map = teamId_gameId.getJSONObject(hostB_name);
            if(hostA_map==null||hostB_map==null){
                continue;
            }
            JSONArray cas_same = getSameMatchCode(hostA_map, hostB_map,hostA_name,hostB_name);
            PlDataSetUtils.setGameHostABSameMatch(gameName,hostA_name+"_"+hostB_name,cas_same);
            logger.info("同一比赛对应数据（"+gameName+"）（"+hostA_name+"_"+hostB_name+"）>>>size:"+cas_same.size()+">>>内容（matchId）:"+cas_same.toString());
        }
        //队伍更新
        SysDictData gameDict = PlDataMakeBestUtils.getGameDictByGameName(gameName);
        PlTeamMakeUtils.setTeam(gameDict);
    }

    /**
     * 所有比赛包装为Map(队伍id:队伍id,比赛id)
     * @param dataJson
     * @param host
     * @return
     */
    public static Map matchMesCase(JSONObject dataJson,String host) {
        Map<String,String> map = new HashMap<>();
        Date nowDate = DateUtils.getNowDate();
        //去除12小时后的比赛
        Date beforeDate = DateUtils.addHours(nowDate,9);
        //雷火包装
        if (host.equals("lh")) {
            String start_datetime = dataJson.getString("start_datetime").trim();
            Date date = DateUtils.parseDate(start_datetime);
            //去除已经开始得比赛
//            if(nowDate.getTime()>date.getTime()){
//                continue;
//            }
            if(beforeDate.getTime()<date.getTime()){
                return map;
            }
            String home_id = getTeamId("lh", dataJson.getJSONObject("home").getString("team_id"));
            if(home_id==null){
                return map;
            }
            String away_id = getTeamId("lh", dataJson.getJSONObject("away").getString("team_id"));
            if(away_id==null){
                return map;
            }
            map.put(home_id+"_"+away_id,dataJson.getString("event_id"));
        }

        //雷电竞包装
        if (host.equals("ldj")) {
//            JSONObject ldj_json = JSONObject.parseObject(ldj.toString());
            Date start_time = DateUtils.parseDate(dataJson.getString("start_time").trim());
            //去除已經開始的比賽
//            if(nowDate.getTime()>start_time.getTime()){
//                continue;
//            }
            if(beforeDate.getTime()<start_time.getTime()){
                return map;
            }
            String home_name = JSONObject.parseObject(dataJson.getJSONArray("team").get(0).toString()).getString("team_id");
            String away_name = JSONObject.parseObject(dataJson.getJSONArray("team").get(1).toString()).getString("team_id");
            String home_id = getTeamId("ldj", home_name);
            if(home_id==null){
                return map;
            }
            String away_id = getTeamId("ldj", away_name);
            if(away_id==null){
                return map;
            }
            map.put(home_id+"_"+away_id,dataJson.getString("id"));
        }

        //亚博包装
        if (host.equals("yb")) {
//            JSONObject yb_json = JSONObject.parseObject(yb.toString());
            //时间筛选
            String startTime=dataJson.getString("PMCDate");
            startTime=startTime.replace("T"," ");
            Date startDate = DateUtils.addHours(DateUtils.parseDate(startTime.substring(0, 19)), 12);
            if(beforeDate.getTime()<startDate.getTime()){
                return map;
            }

            //亚博队伍组装
            String home_id = dataJson.getString("PHTId");
            String away_id = dataJson.getString("PATId");
            String home_local_id = getTeamId("yb", home_id);
            if(home_local_id==null){
                return map;
            }
            String away_local_id = getTeamId("yb", away_id);
            if(away_local_id==null){
                return map;
            }
            map.put(home_local_id+"_"+away_local_id,dataJson.getString("PMatchNo"));
        }
        return map;
    }
    /**
     *
     * @param oddJsonObject
     * @param plMap
     */
    public static Map<String, String> ldj_getMatchType(JSONObject oddJsonObject, PlMatchType plMap) {
        String group_short_name = plMap.getLdjMatchName();
        String match_stage = plMap.getLdjOrder();
        String odd = oddJsonObject.get("odds").toString();
        String team_id = oddJsonObject.getString("team_id");
        //要返回的值
        Map<String, String> l_match_odds = new HashMap<>();
        if (oddJsonObject.get("group_short_name").equals(group_short_name) && oddJsonObject.get("match_stage").equals(match_stage)
                &&oddJsonObject.getInteger("status")!=4) {//状态等于4的是失效的

            if(plMap.getMatchOrderType().equals("1")||plMap.getMatchOrderType().equals("5")){//队伍和VIP队伍
                //存入本地队伍id:odd
                l_match_odds.put(getTeamId("ldj", team_id), odd);
                //存入marketId
                l_match_odds.put("marketId", oddJsonObject.getString("odds_group_id"));
            }
            else if(plMap.getMatchOrderType().equals("2")){//杀敌数让分
                String ldj_v = oddJsonObject.getString("value");
                l_match_odds.put(getTeamId("ldj", team_id)+ldj_v, odd);
                //存入marketId
                l_match_odds.put("marketId_"+ldj_v.substring(1), oddJsonObject.getString("odds_group_id"));
            }
            else if(plMap.getMatchOrderType().equals("3")){//大小
                String ldj_v = oddJsonObject.getString("name");
                ldj_v = ldj_v.substring(0,1)+ldj_v.substring(3);
                l_match_odds.put(ldj_v, odd);
                //存入marketId
                l_match_odds.put("marketId_"+ldj_v.substring(1), oddJsonObject.getString("odds_group_id"));
            }
            else if(plMap.getMatchOrderType().equals("4")){
                String matchType_name = plMap.getMatchType();
                String value = matchType_name.substring(matchType_name.indexOf("(")+1,matchType_name.indexOf(")"));
                //使用value的绝对值进行匹配
                String ldj_v = oddJsonObject.getString("value");
                if(ldj_v.contains(value)){
                    l_match_odds.put(getTeamId("ldj", team_id)+ldj_v, odd);
                }
                //存入marketId
                l_match_odds.put("marketId", oddJsonObject.getString("odds_group_id"));
            }
        }
        return l_match_odds;
    }

    /**
     * 获取队伍id
     * @param hostName
     * @param hostTeamId
     * @return
     */
    public static String getTeamId(String hostName,String hostTeamId) {
        IPlTeamService plTeamService = (IPlTeamService) ApplicationContextUtil.getBean("plTeamServiceImpl");
        PlTeam plTeam = new PlTeam();
        if(hostName.equals("ldj")){
            plTeam.setLdjId(hostTeamId);
        }
        if(hostName.equals("yb")){
            plTeam.setYbId(hostTeamId);
        }
        if(hostName.equals("lh")){
            plTeam.setLhId(hostTeamId);
        }
        List<PlTeam> plTeams = plTeamService.selectPlTeamList(plTeam);
        //若为空则说明此hostTeamid不存在
        if(plTeams.size()<1){
            return null;
        }
        return plTeams.get(0).getId().toString();
    }
    /**
     * 比对不同网站已经封装过的信息，找出相同的比赛
     * @param hostA_map
     * @param hostB_map
     * @param hostA_name
     * @param hostB_name
     * @return
     */
    public static JSONArray getSameMatchCode(JSONObject hostA_map, JSONObject hostB_map, String hostA_name, String hostB_name) {
        JSONArray host_code = new JSONArray();
        for (String hostA:hostA_map.keySet()) {
            for (String hostB:hostB_map.keySet()) {
                String[] hostB_split = hostB.split("_");
                if(hostA.equals(hostB_split[0]+"_"+hostB_split[1])||hostA.equals(hostB_split[1]+"_"+hostB_split[0])){
                    Map<String,String> m = new HashMap<>();
                    m.put(hostA_name,hostA_map.getString(hostA));
                    m.put(hostB_name,hostB_map.getString(hostB));
                    host_code.add(m);
                }
            }
        }
        return host_code;
    }

    /**
     * @param yb_teamMap 队伍code ：队伍全称
     * @param matchJsonObject
     */
    public static Map<String, String> yb_getMatchMap(Map<String, String> yb_teamMap,  JSONObject matchJsonObject,PlMatchType plMap) {
        String winName = plMap.getYbMatchName();
        String GameOrder = plMap.getYbOrder();
        //要返回的值
        Map<String, String> yb_teamOddMap = new HashMap<>();;
        if (matchJsonObject.getInteger("Status")!=2) {//已知2是暂停
            JSONArray odds = matchJsonObject.getJSONArray("Odds");
            //适用于只有一组的情况
            JSONArray selArray = odds.getJSONObject(0).getJSONArray("SEL");
            if(plMap.getMatchOrderType().equals("1")||plMap.getMatchOrderType().equals("5")){//队伍
                //分别取出两个赔率(适用于只有一组的情况)
                JSONObject sel1 = selArray.getJSONObject(0);
                JSONObject sel2 = selArray.getJSONObject(1);
                if (matchJsonObject.getString("GTCode").equals(winName) && matchJsonObject.getString("GameOrder").equals(GameOrder)){
                    yb_teamOddMap.put(yb_teamMap.get(sel1.getString("SCode")), sel1.getString("Odds"));
                    yb_teamOddMap.put(yb_teamMap.get(sel2.getString("SCode")), sel2.getString("Odds"));
                }
            }
            else if(plMap.getMatchOrderType().equals("2")){//局内让分
                if (matchJsonObject.getString("GTCode").equals(winName) && matchJsonObject.getString("GameOrder").equals(GameOrder)){
                    for (Object o :odds) {
                        JSONArray oddContent = JSONObject.parseObject(o.toString()).getJSONArray("SEL");
                        //分别取出两个赔率
                        JSONObject sel1 = oddContent.getJSONObject(0);
                        JSONObject sel2 = oddContent.getJSONObject(1);
                        //sel1和2的HDP是一样的
                        String value = sel1.getString("HDP");
                        //确认哪个是+哪个是-
                        String SName1 = sel1.getString("SName");
                        String SName2 = sel2.getString("SName");
                        //确认符号
                        String fuhao1 = SName1.substring(SName1.indexOf("}")+1,SName1.indexOf("{HDP}")).trim();
                        String fuhao2 = SName2.substring(SName2.indexOf("}")+1,SName2.indexOf("{HDP}")).trim();
                        //存入
                        String key1 = yb_teamMap.get(sel1.getString("SCode")) + fuhao1 + value;
                        String key2 = yb_teamMap.get(sel2.getString("SCode")) + fuhao2 + value;
                        yb_teamOddMap.put(key1, sel1.getString("Odds"));
                        yb_teamOddMap.put(key2, sel2.getString("Odds"));
                    }
                }

            }
            else if(plMap.getMatchOrderType().equals("3")){//大小
                if (matchJsonObject.getString("GTCode").equals(winName) && matchJsonObject.getString("GameOrder").equals(GameOrder)) {
                    for (Object o :odds) {
                        JSONArray oddContent = JSONObject.parseObject(o.toString()).getJSONArray("SEL");
                        //分别取出两个赔率
                        JSONObject sel1 = oddContent.getJSONObject(0);
                        JSONObject sel2 = oddContent.getJSONObject(1);
                        String hdp = Double.parseDouble(sel1.getString("HDP"))+"";
                        String sname1 = sel1.getString("SName").replace("于", "");
                        String sname2 = sel2.getString("SName").replace("于", "");
                        yb_teamOddMap.put(sname1+hdp, sel1.getString("Odds"));
                        yb_teamOddMap.put(sname2+hdp, sel2.getString("Odds"));
                    }
                }
            }
            //数据类型 teamid+1.5:odd
            else if(plMap.getMatchOrderType().equals("4")){//让局
                if (matchJsonObject.getString("GTCode").startsWith(winName) && matchJsonObject.getString("GameOrder").equals(GameOrder)){
                    //分别取出两个赔率(适用于只有一组的情况)
                    JSONObject sel1 = selArray.getJSONObject(0);
                    JSONObject sel2 = selArray.getJSONObject(1);
                    //确认哪个是+哪个是-
                    String gtName = matchJsonObject.getString("GTName");
                    String value = gtName.substring(gtName.indexOf("让")+1,gtName.indexOf("局")).trim();
                    String matchType_name = plMap.getMatchType();
                    String match_value = matchType_name.substring(matchType_name.indexOf("(")+1,matchType_name.indexOf(")"));
                    //正负1.5字符串都是包含1.5的
                    if(value.equals(match_value)){
                        String key1 = yb_teamMap.get(sel1.getString("SCode")) + "+" + value;
                        String key2 = yb_teamMap.get(sel2.getString("SCode")) + "+" + value;
                        yb_teamOddMap.put(key1, sel1.getString("Odds"));
                        yb_teamOddMap.put(key2, sel2.getString("Odds"));
                        if(gtName.contains("{TeamA}")){
                            yb_teamOddMap.put(yb_teamMap.get(sel1.getString("SCode"))+"-"+value,yb_teamOddMap.remove(key1));
                        }else if(gtName.contains("{TeamB}")){
                            yb_teamOddMap.put(yb_teamMap.get(sel2.getString("SCode"))+"-"+value,yb_teamOddMap.remove(key2));
                        }
                    }
                }
            }

        }
        return yb_teamOddMap;
    }

}
